package org.edu.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

import javax.servlet.ServletContext;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.interceptor.RequestAware;
import org.edu.service.DeptService;
import org.edu.service.TreeNodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionSupport;
/**
 * <h2>下载文件</h2>
 * <p>已在方法上注明方法作用</p>
 * <p>该类详细配置了下载文件的方法</p>
 * @author 谢圣强
 * @version 2.0
 */
@Controller
@ParentPackage("struts-default")
// 表示继承的父包
// 父包
@Namespace("/downfile")
@Result(name = "success", location = "/examples/section.jsp")
public class DownFileAction extends ActionSupport implements RequestAware {
	/**
	 * 
	 */
	private static final long serialVersionUID = 6415535992838573766L;
	private static final Logger logger = Logger.getLogger(DownFileAction.class);
	public static final String DOWN_FILE_NAME = "部门信息表-模版.xls";

	private String fileName;// 下载文件 初始的通过param指定的文件名属性
	private Map<String, Object> request;
	private String inputName;// 输出流name
	public InputStream inputStream;// 输出流
	private String inputPath;// 自定义 文件位置
	private int bufferSize;

	@Autowired
	private DeptService deptService;
	@Autowired
	private TreeNodeService treeNodeService;

	/*
	 * 其中主要使用的参数是： contentType 指定下载文件的文件类型 —— application/octet-stream表示无限制
	 * inputName 流对象名 ——比如这里写inputStream，它就会自动去找Action中的getInputStream方法。
	 * contentDisposition 使用经过转码的文件名作为下载文件名
	 * ——默认格式是attachment;filename="${fileName}"，将调用该Action中的getFileName方法。
	 * bufferSize 下载文件的缓冲大小
	 */
	/**
	 * 下载模版
	 * 
	 * @return
	 */
	@Action(value = "downstencil", results = { @Result(name = "success", type = "stream", params = {
			"contentType", "application/vnd.ms-excel", "inputName",
			"inputStream", "contentDisposition",
			"attachment;filename=\"${downloadFileName}\"", "bufferSize", "4096" }) }, params = {
			"inputPath", DOWN_FILE_NAME })
	public String downStencil() throws Exception {
		logger.info("开始下载文件：" + DOWN_FILE_NAME);
		// System.out.println(1);
		try {
			setFileName(DOWN_FILE_NAME);
		} catch (Exception e) {
			logger.info("下载文件失败！请稍后重试");
		}
		return SUCCESS;
	}

	/**
	 * 导出
	 * 
	 * @return
	 */
	@Action(value = "dataexport", results = { @Result(name = "success", type = "stream", params = {
			"contentType", "application/vnd.ms-excel", "inputName",
			"inputStream", "contentDisposition",
			"attachment;filename=\"${downloadFileName}\"", "bufferSize", "4096" }) }, params = {
			"inputPath", UpFileAction.FILE_NAME })
	public String dataExport() {
		logger.info("开始导出数据文件，文件名：" + UpFileAction.FILE_NAME);
		try {
			setFileName(UpFileAction.FILE_NAME);
			ServletContext rel = ServletActionContext.getServletContext();

			File downFile = new File(rel.getRealPath("xls") + "\\"
					+ UpFileAction.FILE_NAME);
//			System.out.println("导出文件路径：" + downFile.getAbsolutePath());
			deptService.datawritxls(downFile);
			logger.info("开始下载文件：" + UpFileAction.FILE_NAME);
		} catch (Exception e) {
			logger.info("下载文件失败！请稍后重试");
		}
		return SUCCESS;
	}

	/**
	 * 获取 文件流句柄
	 * 
	 * @return
	 * @throws IOException
	 */
	public InputStream getInputStream() throws IOException {
//		System.out.println("getInputStream()被调用");
		ServletContext rel = ServletActionContext.getServletContext();
		File downFile = new File(rel.getRealPath("xls") + "\\" + inputPath);
//		System.out.println(inputPath);
		return new FileInputStream(downFile);
	}

	/**
	 * 获取文件名 但是 在params =｛｝ 没有自己定义的话需要手动设置
	 * 
	 * @return
	 */
	public String getDownloadFileName() {
//		System.out.println("getDownloadFileName()被调用:fileName=" + fileName);
		return fileName;
	}

	/**
	 * 设置下载文件的名字
	 * 
	 * @param fileName
	 * @throws UnsupportedEncodingException
	 */
	public void setFileName(String fileName)
			throws UnsupportedEncodingException {
		String agent = ServletActionContext.getRequest()
				.getHeader("User-agent");
		// 如果浏览器是IE浏览器，就得进行编码转换
//		System.out.println("setFileName()被调用");
		if (agent.contains("MSIE")) {
			this.fileName = URLEncoder.encode(fileName, "UTF-8");
		} else {
			this.fileName = new String(fileName.getBytes(), "ISO-8859-1");
		}
	}

	/**
	 * 获得文件流 栈
	 * 
	 * @return
	 */
	public String getInputName() {
//		System.out.println("getInputName()被调用");
		return inputName;
	}

	/**
	 * 
	 * @param inputName
	 */
	public void setInputName(String inputName) {
//		System.out.println("setInputName被调用");
		this.inputName = inputName;
	}

	public String getInputPath() {
		return inputPath;
	}

	public void setInputPath(String inputPath) {
		this.inputPath = inputPath;
	}

	public Map<String, Object> getRequest() {
		return request;
	}

	public void setRequest(Map<String, Object> request) {
		this.request = request;
	}

	/**
	 * 设置 流大小
	 * @return
	 */
	public int getBufferSize() {
//		System.out.println("getBufferSize()被调用" + bufferSize);
		bufferSize = 4096;
		return bufferSize;
	}

	public void setBufferSize(int bufferSize) {
		this.bufferSize = bufferSize;
	}

	public void setInputStream(InputStream inputStream) {
//		System.out.println("setInputStream()被调用");
		this.inputStream = inputStream;
	}

}
